﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace SAFE.API
{
    public class Serializer
    {
        public static object ToObject(string json, Type type)
        {
            if (!string.IsNullOrEmpty(json))
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
                    return serializer.ReadObject(ms);
                }
            }
            return null;
        }

        public static string ToString(object obj, Type type)
        {
            if (obj != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    DataContractJsonSerializer dtcontract = new DataContractJsonSerializer(type);
                    dtcontract.WriteObject(ms, obj);
                    return System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
                }
            }
            return string.Empty;
        }
    }
}
